<template>
  <div class="chat-group-side">
    <div v-show="!group.quit" class="search">
      <el-input placeholder="搜索群成员" v-model="searchText" size="small">
        <i class="el-icon-search el-input__icon" slot="prefix"> </i>
      </el-input>
    </div>
    <el-scrollbar v-show="!group.quit" ref="scrollbar" :style="'height: ' + scrollHeight + 'px'">
      <div class="member-list">
        <div class="member-tools">
          <div class="tool-btn" title="邀请好友进群聊" @click="onInvite()">
            <i class="el-icon-plus"></i>
          </div>
          <div class="tool-text">邀请</div>
          <add-group-member ref="addGroupMember" :groupId="group.id" :members="groupMembers"
            @reload="$emit('reload')"></add-group-member>
        </div>
        <div class="member-tools" v-if="isOwner">
          <div class="tool-btn" title="选择成员移出群聊" @click="onRemove()">
            <i class="el-icon-minus"></i>
          </div>
          <div class="tool-text">移除</div>
          <group-member-selector ref="removeSelector" title="选择成员进行移除" :group="group"
            @complete="onRemoveComplete"></group-member-selector>
        </div>
        <div v-for="(member, idx) in showMembers" :key="member.id">
          <group-member v-if="idx < showMaxIdx" class="group-side-member" :member="member"></group-member>
        </div>
      </div>
    </el-scrollbar>
    <el-divider v-if="!group.quit" content-position="center"></el-divider>

    <!-- 群聊信息卡片 -->
    <div v-if="!group.quit" class="group-info-card">
      <!-- 头像区域 -->
      <div class="avatar-section">
        <div class="avatar-wrapper">
          <file-upload v-if="isOwner && editing" class="avatar-uploader" :action="imageAction" :showLoading="true"
            :maxSize="maxSize" @success="onUploadSuccess"
            :fileTypes="['image/jpeg', 'image/png', 'image/jpg', 'image/webp']">
            <img v-if="group.headImage" :src="group.headImage" class="avatar">
            <div v-else class="avatar-placeholder">
              <i class="fas fa-camera"></i>
              <span>上传头像</span>
            </div>
          </file-upload>
          <head-image v-else class="avatar" :size="80" :url="group.headImage"
            :name="group.showGroupName" radius="12px" type="group">
          </head-image>
        </div>
        <div class="group-basic-info">
          <h3 class="group-name">{{ group.showGroupName }}</h3>
          <p class="member-count">{{ showMembers.length }} 名成员</p>
        </div>
      </div>

      <!-- 表单区域 -->
      <el-form class="group-form" :model="group" :rules="rules" ref="groupForm" size="small" label-position="top">
        <div class="form-row">
          <el-form-item label="群聊名称" prop="name" class="form-item-required">
            <el-input v-model="group.name" :disabled="!isOwner || !editing" maxlength="20"
              placeholder="请输入群聊名称"></el-input>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="群主">
            <el-input :value="ownerName" disabled></el-input>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="群公告">
            <el-input v-model="group.notice" :disabled="!isOwner || !editing" type="textarea"
              :rows="2" maxlength="1024" placeholder="群主未设置群公告"></el-input>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="群名备注">
            <el-input v-model="group.remarkGroupName" :disabled="!editing" maxlength="20"
              :placeholder="group.name || '设置群名备注'"></el-input>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="我在本群的昵称">
            <el-input v-model="group.remarkNickName" :disabled="!editing" maxlength="20"
              :placeholder="userStore.userInfo.nickName || '设置群内昵称'"></el-input>
          </el-form-item>
        </div>

        <!-- 操作按钮组 -->
        <div class="action-buttons">
          <template v-if="editing">
            <el-button type="success" size="small" @click="onSaveGroup()" :loading="saving">
              <i class="fas fa-check"></i> 保存
            </el-button>
            <el-button size="small" @click="onCancelEdit()">
              <i class="fas fa-times"></i> 取消
            </el-button>
          </template>
          <template v-else>
            <el-button type="primary" size="small" @click="onStartEdit()">
              <i class="fas fa-edit"></i> {{ isOwner ? '编辑群聊' : '编辑资料' }}
            </el-button>
            <el-button v-if="!isOwner" type="danger" size="small" plain @click="onQuit()">
              <i class="fas fa-sign-out-alt"></i> 退出群聊
            </el-button>
          </template>
        </div>

        <!-- 编辑提示 -->
        <div v-if="isOwner && editing" class="edit-tip">
          <i class="fas fa-info-circle"></i>
          <span>作为群主，您可以修改群聊名称、群公告和头像</span>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import AddGroupMember from '../IMGroup/AddGroupMember.vue';
import GroupMember from '../IMGroup/GroupMember.vue';
import GroupMemberSelector from '../IMGroup/GroupMemberSelector.vue';
import FileUpload from '../common/FileUpload.vue';
import HeadImage from '../common/HeadImage.vue';
import { getGroupMembersApi, modifyGroupApi, removeGroupMembersApi, quitGroupApi } from '@/api/imGroup.js';
import avatarCache from '@/utils/im/avatarCache.js';

export default {
  name: "chatGroupSide",
  components: {
    AddGroupMember,
    GroupMember,
    GroupMemberSelector,
    FileUpload,
    HeadImage
  },
  data() {
    return {
      searchText: "",
      editing: false,
      saving: false,
      showMaxIdx: 50,
      maxSize: 5 * 1024 * 1024, // 5MB
      imageAction: 'image', // 用于FileUpload组件判断上传类型
      originalGroupData: {}, // 保存编辑前的原始数据
      rules: {
        name: [{
          required: true,
          message: '请输入群聊名称',
          trigger: 'blur'
        }]
      }
    }
  },
  props: {
    group: {
      type: Object
    },
    groupMembers: {
      type: Array
    }
  },
  methods: {
    onClose() {
      this.$emit('close');
    },
    onInvite() {
      this.$refs.addGroupMember.open()
    },
    onRemove() {
      // 群主不显示
      let hideIds = [this.group.ownerId];
      this.$refs.removeSelector.open(50, [], [], hideIds);
    },
    onRemoveComplete(members) {
      let userIds = members.map(m => m.userId);
      let data = {
        groupId: this.group.id,
        userIds: userIds
      }
      removeGroupMembersApi(data).then(() => {
        this.$emit('reload');
        this.$message.success(`您移除了${userIds.length}位成员`);
      }).catch((error) => {
        this.$message.error("移除成员失败：" + (error.message || "未知错误"));
      })
    },
    loadGroupMembers() {
      getGroupMembersApi(this.group.id).then((res) => {
        this.groupMembers = res.data;
      }).catch((error) => {
        console.error("加载群组成员失败：", error);
      })
    },
    onUploadSuccess(data) {
      // 头像上传成功后更新群聊头像
      this.group.headImage = data.originUrl;
      this.group.headImageThumb = data.thumbUrl;

      // 清理头像缓存，确保显示最新头像
      avatarCache.removeAvatar(this.group.id, 'group');

      this.$message.success("头像上传成功");
    },
    onStartEdit() {
      // 保存编辑前的原始数据
      this.originalGroupData = JSON.parse(JSON.stringify(this.group));
      this.editing = true;
    },
    onCancelEdit() {
      // 恢复原始数据
      Object.assign(this.group, this.originalGroupData);
      this.editing = false;
      this.originalGroupData = {};
      this.$message.info("已取消编辑");
    },
    onSaveGroup() {
      // 表单验证
      this.$refs['groupForm'].validate((valid) => {
        if (valid) {
          this.saving = true;
          let vo = this.group;
          modifyGroupApi(vo).then((res) => {
            this.editing = false;
            this.saving = false;
            this.originalGroupData = {};
            this.groupStore.updateGroup(res.data);
            this.$emit('reload');
            this.$message.success("修改成功");
          }).catch((error) => {
            this.saving = false;
            this.$message.error("修改失败：" + (error.message || "未知错误"));
          })
        }
      });
    },
    onQuit() {
      this.$confirm('退出群聊后将不再接受群里的消息，确认退出吗？', '确认退出?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        quitGroupApi(this.group.id).then(() => {
          this.groupStore.removeGroup(this.group.id);
          this.chatStore.removeGroupChat(this.group.id);
          this.$message.success("已退出群聊");
        }).catch((error) => {
          this.$message.error("退出群聊失败：" + (error.message || "未知错误"));
        });
      })
    },
    onScroll(e) {
      const scrollbar = e.target;
      // 滚到底部
      if (scrollbar.scrollTop + scrollbar.clientHeight >= scrollbar.scrollHeight - 30) {
        if (this.showMaxIdx < this.showMembers.length) {
          this.showMaxIdx += 30;
        }
      }
    }
  },
  computed: {
    mine() {
      return this.userStore.userInfo;
    },
    ownerName() {
      let member = this.groupMembers.find((m) => m.userId == this.group.ownerId);
      return member && member.showNickName;
    },
    isOwner() {
      return this.group.ownerId == this.mine.id;
    },
    showMembers() {
      return this.groupMembers.filter((m) => !m.quit && m.showNickName.includes(this.searchText))
    },
    scrollHeight() {
      return Math.min(400, 80 + this.showMembers.length / 5 * 80);
    }
  },
  mounted() {
    let scrollWrap = this.$refs.scrollbar.$el.querySelector('.el-scrollbar__wrap');
    scrollWrap.addEventListener('scroll', this.onScroll);
  }
}
</script>

<style lang="scss" scoped>
.chat-group-side {
  position: relative;

  .search {
    padding: 10px;
  }

  .el-divider--horizontal {
    margin: 0;
  }

  // 群聊信息卡片样式
  .group-info-card {
    padding: var(--im-spacing-lg);
    background: var(--im-bg-primary);
    border-radius: var(--im-border-radius-lg);
    margin: var(--im-spacing-base) 0;

    // 头像区域样式
    .avatar-section {
      display: flex;
      align-items: center;
      gap: var(--im-spacing-lg);
      margin-bottom: var(--im-spacing-xl);
      padding-bottom: var(--im-spacing-lg);
      border-bottom: 1px solid var(--im-border-color-light);

      .avatar-wrapper {
        flex-shrink: 0;

        .avatar-uploader {
          .el-upload {
            border: 2px dashed var(--im-border-color) !important;
            border-radius: var(--im-border-radius-lg) !important;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            width: 80px;
            height: 80px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: var(--im-bg-secondary);
            transition: all var(--im-transition-base);

            &:hover {
              border-color: var(--im-color-primary) !important;
              background: var(--im-bg-hover);
              transform: translateY(-2px);
              box-shadow: var(--im-box-shadow-hover);
            }

            .avatar-placeholder {
              display: flex;
              flex-direction: column;
              align-items: center;
              gap: var(--im-spacing-xs);
              color: var(--im-text-color-secondary);
              font-size: var(--im-font-size-xs);

              i {
                font-size: 20px;
                color: var(--im-color-primary-light-4);
              }

              span {
                font-size: 10px;
                text-align: center;
                line-height: 1.2;
              }
            }

            .avatar {
              width: 80px;
              height: 80px;
              display: block;
              border-radius: var(--im-border-radius-lg);
              object-fit: cover;
            }
          }
        }

        .avatar {
          border-radius: var(--im-border-radius-lg);
          box-shadow: var(--im-box-shadow-sm);
        }
      }

      .group-basic-info {
        flex: 1;
        min-width: 0;

        .group-name {
          font-size: var(--im-font-size-lg);
          font-weight: var(--im-font-weight-semibold);
          color: var(--im-text-color-primary);
          margin: 0 0 var(--im-spacing-xs) 0;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .member-count {
          font-size: var(--im-font-size-sm);
          color: var(--im-text-color-secondary);
          margin: 0;
          display: flex;
          align-items: center;
          gap: var(--im-spacing-xs);

          &::before {
            content: '\f0c0';
            font-family: 'Font Awesome 5 Free';
            font-weight: 900;
            font-size: 12px;
            color: var(--im-color-primary-light-4);
          }
        }
      }
    }

    // 表单样式
    .group-form {
      .form-row {
        margin-bottom: var(--im-spacing-base);

        &:last-child {
          margin-bottom: 0;
        }
      }

      .el-form-item {
        margin-bottom: 0 !important;

        .el-form-item__label {
          font-size: var(--im-font-size-sm) !important;
          color: var(--im-text-color-secondary) !important;
          font-weight: var(--im-font-weight-medium) !important;
          padding-bottom: var(--im-spacing-xs) !important;
          line-height: 1.2 !important;
        }

        &.form-item-required .el-form-item__label::after {
          content: ' *';
          color: var(--im-color-danger);
          font-weight: bold;
        }

        .el-input {
          .el-input__wrapper {
            border-radius: var(--im-border-radius-base) !important;
            border: 1px solid var(--im-border-color) !important;
            background: var(--im-bg-secondary) !important;
            transition: all var(--im-transition-base) !important;
            box-shadow: none !important;

            &:hover {
              border-color: var(--im-color-primary-light-4) !important;
            }

            &.is-focus {
              border-color: var(--im-color-primary) !important;
              box-shadow: 0 0 0 2px var(--im-color-primary-light-8) !important;
            }

            .el-input__inner {
              font-size: var(--im-font-size-sm) !important;
              color: var(--im-text-color-primary) !important;
              background: transparent !important;

              &::placeholder {
                color: var(--im-text-color-placeholder) !important;
                font-size: var(--im-font-size-xs) !important;
              }

              &:disabled {
                color: var(--im-text-color-disabled) !important;
                background: var(--im-bg-tertiary) !important;
              }
            }
          }

          &.is-disabled .el-input__wrapper {
            background: var(--im-bg-tertiary) !important;
            border-color: var(--im-border-color-light) !important;
          }
        }

        .el-textarea {
          .el-textarea__inner {
            border-radius: var(--im-border-radius-base) !important;
            border: 1px solid var(--im-border-color) !important;
            background: var(--im-bg-secondary) !important;
            font-size: var(--im-font-size-sm) !important;
            color: var(--im-text-color-primary) !important;
            resize: none !important;
            transition: all var(--im-transition-base) !important;

            &::placeholder {
              color: var(--im-text-color-placeholder) !important;
              font-size: var(--im-font-size-xs) !important;
            }

            &:hover {
              border-color: var(--im-color-primary-light-4) !important;
            }

            &:focus {
              border-color: var(--im-color-primary) !important;
              box-shadow: 0 0 0 2px var(--im-color-primary-light-8) !important;
            }

            &:disabled {
              background: var(--im-bg-tertiary) !important;
              border-color: var(--im-border-color-light) !important;
              color: var(--im-text-color-disabled) !important;
            }
          }
        }
      }
    }

    // 操作按钮组样式
    .action-buttons {
      display: flex;
      gap: var(--im-spacing-sm);
      margin-top: var(--im-spacing-lg);
      padding-top: var(--im-spacing-lg);
      border-top: 1px solid var(--im-border-color-light);

      .el-button {
        flex: 1;
        border-radius: var(--im-border-radius-base) !important;
        font-size: var(--im-font-size-sm) !important;
        padding: var(--im-spacing-sm) var(--im-spacing-base) !important;
        transition: all var(--im-transition-base) !important;

        i {
          margin-right: var(--im-spacing-xs);
          font-size: var(--im-font-size-xs);
        }

        &.el-button--primary {
          background: var(--im-color-primary) !important;
          border-color: var(--im-color-primary) !important;

          &:hover {
            background: var(--im-color-primary-light-1) !important;
            border-color: var(--im-color-primary-light-1) !important;
            transform: translateY(-1px);
            box-shadow: var(--im-box-shadow-hover);
          }
        }

        &.el-button--success {
          background: var(--im-color-success) !important;
          border-color: var(--im-color-success) !important;

          &:hover {
            background: #5daf34 !important;
            border-color: #5daf34 !important;
            transform: translateY(-1px);
            box-shadow: var(--im-box-shadow-hover);
          }
        }

        &.el-button--danger {
          &.is-plain {
            color: var(--im-color-danger) !important;
            border-color: var(--im-color-danger) !important;
            background: transparent !important;

            &:hover {
              background: var(--im-color-danger) !important;
              color: white !important;
              transform: translateY(-1px);
              box-shadow: var(--im-box-shadow-hover);
            }
          }
        }

        &:not(.el-button--primary):not(.el-button--success):not(.el-button--danger) {
          color: var(--im-text-color-secondary) !important;
          border-color: var(--im-border-color) !important;
          background: var(--im-bg-secondary) !important;

          &:hover {
            color: var(--im-color-primary) !important;
            border-color: var(--im-color-primary) !important;
            background: var(--im-bg-hover) !important;
            transform: translateY(-1px);
            box-shadow: var(--im-box-shadow-hover);
          }
        }
      }
    }

    // 编辑提示样式
    .edit-tip {
      margin-top: var(--im-spacing-base);
      padding: var(--im-spacing-sm) var(--im-spacing-base);
      background: linear-gradient(135deg, var(--im-color-primary-light-9), var(--im-color-primary-light-8));
      border: 1px solid var(--im-color-primary-light-6);
      border-radius: var(--im-border-radius-base);
      font-size: var(--im-font-size-xs);
      color: var(--im-color-primary-dark-1);
      display: flex;
      align-items: center;
      gap: var(--im-spacing-xs);

      i {
        color: var(--im-color-primary);
        font-size: var(--im-font-size-sm);
      }

      span {
        line-height: 1.4;
      }
    }
  }

  .member-list {
    padding: 10px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    font-size: 14px;
    text-align: center;

    .group-side-member {
      margin-left: 5px;
    }

    .member-tools {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 54px;
      margin-left: 5px;

      .tool-btn {
        width: 38px;
        height: 38px;
        line-height: 38px;
        border: var(--im-border);
        font-size: 14px;
        cursor: pointer;
        box-sizing: border-box;

        &:hover {
          border: #aaaaaa solid 1px;
        }
      }

      .tool-text {
        font-size: 12px;
        text-align: center;
        width: 100%;
        height: 30px;
        line-height: 30px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden
      }
    }
  }

  .form {
    text-align: left;
    padding: 10px;
    height: 30%;

    .el-form-item {
      margin-bottom: 12px;

      .el-form-item__label {
        padding: 0;
        line-height: 30px;
      }

      .el-textarea__inner {
        min-height: 100px !important;
      }
    }

    .el-input__inner,
    .el-textarea__inner {
      color: var(--im-text-color) !important;
    }


  }

  // 优化整体布局
  .el-form-item {
    margin-bottom: 0px !important;
  }

  // 滚动条优化
  .el-scrollbar__wrap {
    overflow-x: hidden !important;
  }

  // 响应式优化
  @media (max-width: 768px) {
    .group-info-card {
      padding: var(--im-spacing-base);

      .avatar-section {
        flex-direction: column;
        text-align: center;
        gap: var(--im-spacing-base);

        .group-basic-info {
          .group-name {
            font-size: var(--im-font-size-base);
          }
        }
      }

      .action-buttons {
        flex-direction: column;

        .el-button {
          flex: none;
        }
      }
    }
  }
}
</style>
